<script>
  export default function () {
    function initUploadInput() {
      var inputObj = document.createElement('input')
      inputObj.setAttribute('id', 'file')
      inputObj.setAttribute('type', 'file')
      inputObj.setAttribute('name', 'file')
      inputObj.setAttribute('style', 'visibility:hidden')
      document.body.appendChild(inputObj)
      inputObj.value
      return inputObj
    }

    const selFile = function (extend) {
      return new Promise((resolve, reject) => {
        // 一定要在这个方法内持有dom对象
        const inputObj = initUploadInput()
        // 注入扩展属性
        extend.forEach((item) => inputObj.setAttribute(item.key, item.value))
        inputObj.click()
        inputObj.addEventListener('change', (e) => {
          if (e.target.files.length > 0) {
            const file = e.target.files[0]
            var reader = new FileReader()
            reader.onload = function (e) {
              var data = e.target.result
              const fileObj = { fileName: file.name, base64: data }
              resolve(fileObj)
            }
            reader.readAsDataURL(file)
          } else {
            reject()
          }
        })
      })
    }
    const selXLS = function () {
      const extend = [{ key: 'accept', value: '.xls, .xlsx' }]
      return selFile(extend)
    }
    return {
      selFile,
      selXLS,
    }
  }
</script>
